package lib

import (
	"GameServer/Common/utils"
	"fmt"
	"reflect"

	"GameServer/Common/data"
	"GameServer/Game/errors"
	"GameServer/Game/m"
)

// 获取宝箱奖励
func getBoxRewards(id uint64, page uint64) (r []m.BaseKV, res []*m.Goods, err error) {
	t, ok := data.Get("BoxRewards", id)
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有找到宝箱配置表id:%d", id))
		return
	}
	boxT := t.(data.BoxReward)

	var rewards []data.WeightV

	for _, item := range boxT.Rewards {
		if item.Page == 0 {
			rewards = append(rewards, data.WeightV{Weight: item.Weight, Value: item})
		}
		if item.Page <= page {
			rewards = append(rewards, data.WeightV{Weight: item.Weight, Value: item})
		}
		if item.Page > page {
			break
		}
	}

	num := utils.RandomInt64(int64(boxT.Range.Min), int64(boxT.Range.Max))
	for i := 0; i < int(num); i++ {
		w := utils.RandomWeight(rewards)
		wReward := w.Value.(data.BoxRewardStuct)
		r = append(r, m.BaseKV{Key: int64(wReward.Key), Val: utils.Int64(wReward.Value)})
		res = append(res, &m.Goods{Tid: int64(wReward.Key), Num: utils.Int64(wReward.Value)})
	}
	return
}

// 使用物品
func UseGood(from string, u *m.User, goodsT data.Good, PSend func(interface{}) error) (uProp *m.UpdateProp, res []*m.Goods, boxResList []*m.BoxRes, err error) {

	layerT, ok := getLayerT(uint64(u.MaxPos.LockBlockTid), uint64(u.MaxPos.LayerId))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有找到层配置信息:Pos%v", u.MaxPos))
		return
	}
	switch goodsT.Effect.(type) {
	case map[string]interface{}:
		mEffect := goodsT.Effect.(map[string]interface{})
		key := mEffect["key"]
		val := mEffect["value"]
		if key == 0 && val == 0 {
			return
		}
		uProp, resGoods, boxResList, err := GiveGoodsByKv(from, u, m.BaseKV{Key: utils.Int64(key), Val: utils.Int64(val)}, PSend)
		if err != nil {
			return nil, nil, nil, err
		}
		return uProp, resGoods, boxResList, nil
	case uint64, float64:
		switch true { // 宝箱
		case int64(goodsT.Category) == data.GoodsCategoryEnum.CategoryLv3:
			kvs, res1, err := getBoxRewards(utils.Uint64(goodsT.Effect), layerT.Page)
			if err != nil {
				return nil, nil, nil, err
			}
			uProp, _, _, err = GiveGoodsByKvList(from, u, kvs, PSend)
			if err != nil {
				return nil, nil, nil, err
			}
			// 捡起礼物宝箱
			if from == "UseGridGoods" && int64(goodsT.Type) == data.GoodsTypeEnum.Gift {
				u.GetUserStatic().AddTypNum(data.StaticTYP.GiftBox, 1)
			}
			boxRes := &m.BoxRes{Tid: int64(goodsT.Id), Res: make([]*m.Goods, 0)}
			boxRes.Res = append(boxRes.Res, res1...)
			boxResList = append(boxResList, boxRes)
			if from == "UseGridGoods" {
				//res = &m.Goods{Tid: int64(goodsT.Id), Num: 1}
				boxx := &m.Goods{Tid: int64(goodsT.Id), Num: 1}
				res = append(res, boxx)
			} else {
				res = res1
			}
			// 成就，记录宝箱里面星星的值
			AchievBoxCard(u, boxResList)
			return uProp, res, boxResList, nil
		case int64(goodsT.Category) == data.GoodsCategoryEnum.CategoryLv6:
			goodsType64 := int64(goodsT.Type)
			if goodsType64 == data.GoodsTypeEnum.Tv {
				kvs, res1, err := getBoxRewards(utils.Uint64(goodsT.Effect), layerT.Page)
				if err != nil {
					return nil, nil, nil, err
				}
				uProp, _, _, err = GiveGoodsByKvList(from, u, kvs, PSend)
				if err != nil {
					return nil, nil, nil, err
				}
				res = res1
				for _, item := range res1 {
					goodsTplTemp, ok := data.Get("Goods", uint64(item.Tid))
					if !ok {
						err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有找到配置表id:%d", item.Tid))
						return nil, nil, nil, err
					}
					goodsTemp := goodsTplTemp.(data.Good)
					if int64(goodsTemp.Category) == data.GoodsCategoryEnum.CategoryLv3 {
						uPropTemp, resGoodsTemp, boxResListTemp, err := UseGood("UseGridGoods", u, goodsTemp, PSend)
						if err != nil {
							return nil, nil, nil, err
						}
						uProp.Merge(uPropTemp)
						boxRes := &m.BoxRes{Tid: int64(goodsTemp.Id), Res: make([]*m.Goods, 0)}
						boxRes.Res = append(boxRes.Res, resGoodsTemp...)
						boxResList = boxResListTemp
					}
				}
				// 成就，记录看广告一次。
				AddAchievProgress(u, data.AchievementType.Watch_ads, 1)
				return uProp, res, boxResList, nil
			} else if goodsType64 == data.GoodsTypeEnum.Crystalball {
				return nil, nil, nil, nil
			} else if goodsType64 == data.GoodsTypeEnum.MagicBookRed || goodsType64 == data.GoodsTypeEnum.MagicBookBlue || goodsType64 == data.GoodsTypeEnum.MagicBookPurple {
				return nil, nil, nil, nil
			}
		default:
			fmt.Println("effect : ", goodsT.Effect)
		}

	default:
		typ := reflect.TypeOf(goodsT.Effect)
		fmt.Println("effect : ", goodsT.Effect, "typ kind:", typ.Kind())
	}
	return
}

func GetGoodInfo(tid int64) (r data.Good, err error) {
	tpl, ok := data.Get("Goods", uint64(tid))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有找到goods配置,id:%d", tid))
		return
	}
	r = tpl.(data.Good)
	return
}

// 是怪，返回true，不是怪，返回false
func IsMonster(tid int64) (ok bool) {
	tpl, ok := data.Get("Goods", uint64(tid))
	if !ok {
		return false
	}
	tplT := tpl.(data.Good)
	// 如果该格子是怪，那么他周围的格子不能解锁
	if int64(tplT.Category) == data.GoodsCategoryEnum.CategoryLv9 && int64(tplT.Type) == data.GoodsTypeEnum.SmallMoster {
		return true
	}
	return false
}
